/**
 * javaHispano 2008
 */
package org.javahispano.jwitter.data.jpa;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.javahispano.jwitter.data.dao.GenericDao;

/**
 * @author javaHispano
 *
 */
public abstract class GenericDaoJpaImpl<K,T> implements GenericDao<K,T> {

	/**
	 * EntityManager de JPA, este atributo es inyectado por Spring automaticamente
	 */
	@PersistenceContext
	protected EntityManager em;
	
	public void setEm(EntityManager em) {
		this.em = em;
	}

	/* (non-Javadoc)
	 * @see org.javahispano.jwitter.data.dao.GenericDao#persist(java.lang.Object)
	 */
	@Override
	public K persist(T entity) {
		em.persist(entity);
		return getClavePrimaria(entity);
	}
	
	/* (non-Javadoc)
	 * @see org.javahispano.jwitter.data.dao.GenericDao#finfById(java.lang.Object)
	 */
	@Override
	public T findById(K id){
		return em.find(getEntityClass(), id);
	}
	
	/* (non-Javadoc)
	 * @see org.javahispano.jwitter.data.dao.GenericDao#update(java.lang.Object)
	 */
	@Override
	public void update(T entity) {
		em.merge(entity);		
	}		
	
	/* (non-Javadoc)
	 * @see org.javahispano.jwitter.data.dao.GenericDao#delete(java.lang.Object)
	 */
	@Override
	public void delete(T entity) {
		em.merge(entity);
		em.remove(entity);		
	}
	
	/* (non-Javadoc)
	 * @see org.javahispano.jwitter.data.dao.GenericDao#delete(java.lang.Object)
	 */
	@Override
	public abstract Collection<T> findAll();
		
	/**
	 * Regresa la el atributo identificador de la entidad
	 * @param entity
	 * @return
	 */
	protected abstract K getClavePrimaria(T entity);
	
	/**
	 * Regresa la clase de la entidad
	 * @return
	 */
	protected abstract Class<T> getEntityClass();

}
